#include "datatest.h"
#include <QJsonObject>
#include <QJsonDocument>

Datatest::Datatest(QWidget *parent) :QWidget(parent),time(60000),common(this){
    db=SQLiteDatabase::getInstance();

    m_pTimer=new QTimer;
    connect(m_pTimer,&QTimer::timeout,this,&Datatest::onCreateData);
    m_pTimer->start(time);

}

void Datatest::onCreateData(){
    QString datetime=common.getDateTime("yyyy-MM-dd HH:mm:ss");
    QString temperatureStr=common.getRandomDoubleStr(21.0,100.0,1);
    QString co2Str=common.getRandomDoubleStr(0.210,1.000,1,true);
    QString humidity = common.getRandomIntStr(0,100); // 生成一个20到50的随机数
    QString light = common.getRandomIntStr(0,100); // 生成一个0到50的随机数
    QString pressure="1MPa";

    QString devicesIdStr;
    QJsonArray devicesArray = db->read("devices");
    int randomInt = common.getRandomInt(1, devicesArray.size()); // Generate a random number between 0 and 5
    if (!devicesArray.isEmpty() && randomInt > 0 && randomInt <= devicesArray.size()) {
        QJsonObject obj = devicesArray.at(randomInt - 1).toObject(); // Use at() and adjust index
        if (obj.contains("device_id")) {
            QJsonValue deviceIdValue = obj.value("device_id");
            if (deviceIdValue.isString()) {
                devicesIdStr = deviceIdValue.toString();
                qDebug() << "devicesIdStr:" << devicesIdStr;
            } else {
                qDebug() << "device_id is not a string";
            }
        } else {
            qDebug() << "device_id key not found in JSON object";
        }
    } else {
        qDebug() << "Invalid randomInt or devicesArray is empty";
    }

    QJsonObject newData;
    newData["timestamp"] = datetime; //时间戳
    newData["temperature"] = temperatureStr;
    newData["humidity"] = humidity;
    newData["light"] = light;
    newData["co2"] = co2Str;
    newData["pressure"] = pressure;
    newData["device_id"] = devicesIdStr;
    db->create("data", newData);
    m_pTimer->start(time);
}
